﻿@using System.Diagnostics.CodeAnalysis
@inherits LayoutComponentBase
@inject HttpClient Http

<Layout ShowFooter="false">
        <Header>
             <Row ItemsPerRow="ItemsPerRow.Twelve">
                   <Row ColSpan="11">
                     <div class="text-center header">
                        <h1>各类API持续更新中</h1>
                     </div>   
                  </Row>
                   <div class="mt-2">
                        <Button Size="Size.Medium" Color="Color.Primary" OnClick="@(async e => await APIModal.Toggle())">新增接口</Button>
                   </div>   
             </Row>
        </Header>
        <Main>
            <div class="text-center main">@Body</div>
        </Main>
        <Footer>
            <div class="text-center footer">Footer</div>
        </Footer>
 </Layout>
 <Modal @ref="APIModal">
    <ModalDialog IsCentered="true" Title="新增API接口" ShowCloseButton="false">
        <BodyTemplate>        
            <div>
                 <BootstrapInput TValue="string" IsAutoFocus="true" IsSelectAllTextOnFocus="true" @bind-Value=@Model.Title  placeholder="标题" />
            </div>
            <div class="mt-2">
                <BootstrapInput TValue="string" IsAutoFocus="true" IsSelectAllTextOnFocus="true" @bind-Value=@Model.Url placeholder="API接口地址" />
            </div>
            <div class="mt-2">
                 <Select TValue="string" Items="RequestTypeItems" @bind-Value=@Model.RequestType></Select>
            </div>
            <div class="mt-2">
                <Select TValue="string"  Items="ReturnFormatItems" @bind-Value=@Model.ReturnFormat></Select>
            </div>
            <div class="mt-2">                 
                 <Row ItemsPerRow="ItemsPerRow.Three">
                     <Switch ValueChanged="@OnValueChanged" Value="@IsRequireParameter"  OnColor="Color.Secondary" OnText="开启请求参数" OffText="关闭请求参数"></Switch>                       
                      <div class="text-center header">
                        <h6 class="mt-2">参数数量：</h6>
                     </div>  
                      <BootstrapInputNumber ShowButton="true" @bind-Value=@ParameterNum Min="@ParameterMinNum" Max="16" Color="Color.None" />
                 </Row>
            </div>
            @if (IsRequireParameter)
            {
                @for (var i = 0; i < ParameterNum; i++)
                {
                   string c = ((char)(65+i)).ToString();
                   <div class="mt-2 text-center header">
                        <h5>第{@(i+1)}个参数</h5>
                   </div>
                   <div class="mt-2">
                       <BootstrapInput TValue="string" IsAutoFocus="true" IsSelectAllTextOnFocus="true" @bind-value="@DynamicDynamicValues[$"RequestParameterName{c}"]"  placeholder="参数名字" />
                   </div>   
                    <div class="mt-2">
                       <BootstrapInput TValue="string" IsAutoFocus="true" IsSelectAllTextOnFocus="true" @bind-value="@DynamicDynamicValues[$"RequestParameterLabel{c}"]"  placeholder="参数显示名称" />
                   </div>   
                   <div class="mt-2">
                       <Select TValue="string"  Items="ParameterTypeItems" @bind-value="@DynamicDynamicValues[$"RequestParameterType{c}"]"></Select>
                   </div> 
                   <div class="mt-2">
                       <Select TValue="string"  Items="ControlTypeItems" @bind-value="@DynamicDynamicValues[$"RequestControlType{c}"]"></Select>
                   </div>   
                   <div class="mt-2">
                       <BootstrapInput TValue="string" IsAutoFocus="true" IsSelectAllTextOnFocus="true" @bind-value="@DynamicDynamicValues[$"RequestParameterValue{c}"]"  placeholder="固定参数：可空，如果有多个请用英文逗号,进行分割" />
                   </div> 
                }
            }
          <div class="mt-2">
                 <Button Size="Size.Medium" Color="Color.Primary" OnClick="@OnClick">新增接口</Button>
           </div>
        </BodyTemplate>
    </ModalDialog>
</Modal>
@code {
    [NotNull]
    private Modal? APIModal { get; set; }

    [NotNull]
    private ApiModel? Model { get; set; } = new ApiModel();

    [Inject]
    [NotNull]
    private DialogService? DialogService { get; set; }

    [Inject]
    [NotNull]
    public MessageService? MessageService { get; set; }

    private bool IsRequireParameter { get; set; } = false;
    private int ParameterNum { get; set; } = 0;
    private string? ParameterMinNum { get; set; } = "0";
    private string? Message { get; set; }

    private class ApiModel
    {
        public string? Url { get; set; }
        public string? Title { get; set; }
        public string? RequestType { get; set; }
        public string? ReturnFormat { get; set; }
        public bool IsRequireParameter { get; set; }
        public virtual List<RequestParameterModel>? RequestParameters { get; set; } = new List<RequestParameterModel>();
    }

    public class RequestParameterModel
    {
        public string? Name { get; set; }
        public string? ParameterType { get; set; }
        public string? ControlType { get; set; }
        public string? Value { get; set; }
        public string? Label { get; set; }
    }

    private IEnumerable<SelectedItem> RequestTypeItems { get; set; } = new[]
    {
            new SelectedItem ("", "请选择请求类型 ...") { Active = true },
            new SelectedItem ("GET", "get") { Active = true },
            new SelectedItem ("POST", "post"),
    };

    private IEnumerable<SelectedItem> ReturnFormatItems { get; set; } = new[]
    {
            new SelectedItem ("", "请选择数据返回格式 ...") { Active = true },
            new SelectedItem ("json", "json"),
            new SelectedItem ("text", "text"),
            new SelectedItem ("image", "image"),
    };

    private IEnumerable<SelectedItem> ParameterTypeItems { get; set; } = new[]
    {
            new SelectedItem ("", "请选择参数类型 ...") { Active = true },
            new SelectedItem ("String", "String"),
            new SelectedItem ("Int", "Int")
    };

    private IEnumerable<SelectedItem> ControlTypeItems { get; set; } = new[]
    {
            new SelectedItem ("", "请选择参数输入控件 ...") { Active = true },
            new SelectedItem ("TextEdit", "TextEdit"),
            new SelectedItem ("Select", "Select")
    };

    private void OnValueChanged(bool val)
    {
        if (val)
        {
            ParameterMinNum = "1";
            ParameterNum = ParameterNum == 0 ? 1 : ParameterNum;

            for (var i = 0; i < ParameterNum; i++)
            {
                string c = ((char)(65+i)).ToString();
                if (!DynamicDynamicValues?.ContainsKey($"RequestParameterName{c}") ?? true) 
                    DynamicDynamicValues?.Add($"RequestParameterName{c}","");     

                if (!DynamicDynamicValues?.ContainsKey($"RequestParameterLabel{c}") ?? true)    
                    DynamicDynamicValues?.Add($"RequestParameterLabel{c}","");

                if (!DynamicDynamicValues?.ContainsKey($"RequestParameterType{c}") ?? true)
                    DynamicDynamicValues?.Add($"RequestParameterType{c}","");

                if (!DynamicDynamicValues?.ContainsKey($"RequestControlType{c}") ?? true)
                    DynamicDynamicValues?.Add($"RequestControlType{c}","");

                if (!DynamicDynamicValues?.ContainsKey($"RequestParameterValue{c}") ?? true)
                    DynamicDynamicValues?.Add($"RequestParameterValue{c}","");
            }
        }
        else
        {
            ParameterMinNum = "0";
            ParameterNum = 0;
        }
        IsRequireParameter = val;
        Model.IsRequireParameter = val;
    }

    bool isFirst = true;
    private Dictionary<string, string>? DynamicDynamicValues = new Dictionary<string, string>();
    private void ValueChanged(ChangeEventArgs a, string label)
    {
        DynamicDynamicValues[label] = a.Value.ToString();
    }

    private string GetValue(string label)
    {
        return DynamicDynamicValues[label];
    }

    private async void OnClick(MouseEventArgs e)
    {
        Model.RequestParameters = new List<RequestParameterModel>();
        if (Model.IsRequireParameter && ParameterNum > 0 && DynamicDynamicValues != null && DynamicDynamicValues.Count > 0)
        {
            for (var i = 0; i < ParameterNum; i++)
            {
                string c = ((char)(65+i)).ToString();
                RequestParameterModel parameterModel = new RequestParameterModel();

                if (DynamicDynamicValues?.ContainsKey($"RequestParameterName{c}") ?? false)
                    parameterModel.Name = GetValue($"RequestParameterName{c}");    

                if (DynamicDynamicValues?.ContainsKey($"RequestParameterLabel{c}") ?? false)    
                    parameterModel.Label = GetValue($"RequestParameterLabel{c}");    

                if (DynamicDynamicValues?.ContainsKey($"RequestParameterType{c}") ?? false)
                    parameterModel.ParameterType = GetValue($"RequestParameterType{c}");    

                if (DynamicDynamicValues?.ContainsKey($"RequestControlType{c}") ?? false)
                    parameterModel.ControlType = GetValue($"RequestControlType{c}");    

                if (DynamicDynamicValues?.ContainsKey($"RequestParameterValue{c}") ?? false)
                    parameterModel.Value = GetValue($"RequestParameterValue{c}");    

                Model?.RequestParameters?.Add(parameterModel);
            }
        }

        var response = await Http.PostAsJsonAsync("/api", Model);
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();

            if (result == "1")
            {
                Model = new ApiModel();
                DynamicDynamicValues = new Dictionary<string, string>();
                IsRequireParameter = false;
                ParameterNum = 0;
                ParameterMinNum = "0";
                await MessageService.Show(new MessageOption()
                {
                    Color = Color.Info,
                    Content = "操作成功",
                    Icon = "fa fa-info-circle",
                    ShowDismiss = true,
                });
            }
            else
            {
                await MessageService.Show(new MessageOption()
                {
                    Color = Color.Danger,
                    Content = result,
                    Icon = "fa fa-info-circle",
                    ShowDismiss = false,
                });                
            }
        }
        else
        {
           await MessageService.Show(new MessageOption()
           {
                Content = "网络异常",
                Icon = "fa fa-info-circle",
                ShowDismiss = true,
           });
        }
    }
}
